//! @Author: DengLibin 
//! @Date:  2022-04-19 15:42:14
//! @Description: 日期模块

use std::{time::SystemTime, ops::Add};

use chrono::{Local, Datelike, NaiveDateTime, Duration};
const DATE_TIME_PATTERN: &str = "%Y-%m-%d %H:%M:%S";
///获取时间戳 毫秒
pub fn get_sys_timestamp_millis() -> u128 {
    let now = SystemTime::now();
    now.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_millis()
}
///获取时间戳 毫秒
pub fn get_chrono_timestamp_millis() -> i64 {
    let now = Local::now().naive_local();
    now.timestamp_millis()
}



///获取本地当前时间 格式化
pub fn get_chrono_local_now_time_str() -> String {
    let now = Local::now().naive_local();
    format_time(&now)
}
///获取年
pub fn get_chrono_local_now_year() -> i32 {
    let now = Local::now().naive_local();
    now.year()
}
///获取月
pub fn get_chrono_local_now_month() -> u32 {
    let now = Local::now().naive_local();
    now.month()
}
///获取日
pub fn get_chrono_local_now_day() ->u32 {
    let now = Local::now().naive_local();
    now.day()
}
///获取年 月 日
pub fn get_chrono_now_year_month_day() ->(i32, u32, u32) {
    let now = Local::now().naive_local();
    (now.year(), now.month(), now.day())
}
///时间戳转日期
pub fn timstamp2datetime(timestamp_sec: i64) -> String {
    let time = timestamp2datetime(timestamp_sec);
    format_time(&time)
}

/// 时间字符串戳转日期
/// 返回时间戳（毫秒）
pub fn timestr2date(datetime: &str)-> Result<i64, String>{
    let r = NaiveDateTime::parse_from_str(datetime, DATE_TIME_PATTERN);

    match r {
        Ok(t) => {Ok(t.timestamp_millis())}
        Err(e) => {Err(e.to_string())}
    }
}
/// 相加 天数 返回时间戳 毫秒
pub fn add_day(timestamp_sec: i64, day: i64) -> i64 {
    let date = timestamp2datetime(timestamp_sec);
    let d = date.add(Duration::days(day));
    d.timestamp_millis()
}



/// 格式化日期
fn format_time(time: &NaiveDateTime) -> String {
    time.format(DATE_TIME_PATTERN).to_string()
}
/// 时间戳转日期
fn timestamp2datetime(timestamp_sec: i64) -> NaiveDateTime {
    NaiveDateTime::from_timestamp(timestamp_sec, 0)
}
    
